/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
package cgl.narada.util.ntlm;

import java.io.IOException;
import java.security.Provider;
import java.security.Security;

/**
 * NTLM Authentication library.  Requires a JCE library with MD4 and
 * DES with no-padding ECB cipher
 *
 * @author  John Yin
 * @version 1.0
 */

public class NTLMAuthen {

    private int m_step = 0;
    private String m_domain = null;
    private String m_hostname = null;
    private String m_username = null;
    private String m_password = null;
    private byte[] m_nonce    = null;

    /**
     * ---------------------------------------------------------------------
     * Specify a specific crypto provider.
     */
    public NTLMAuthen(String providerClassName,
                      String domain,
                      String hostname,
                      String username,
                      String password) throws Exception {
        Class securityProvider = Class.forName(providerClassName);
        Provider p = (Provider)securityProvider.newInstance();
        if (Security.getProvider(p.getName()) == null) {
            Security.addProvider(p);
        }

        m_domain = domain;
        m_hostname = hostname;
        m_username = username;
        m_password = password;
    }

    /**
     * ---------------------------------------------------------------------
     * By default uses the Cryptix libraries.
     */
    public NTLMAuthen(String domain,String hostname,String username,String password) throws Exception {
        this("cryptix.jce.provider.CryptixCrypto",domain,hostname,username,password);
    }

    /**
     * ---------------------------------------------------------------------
     * @return The proxy authentication header for NTLM type 1 message. of
     *         the form "NTLM XXXXXXXXXXXXX"
     * @exception IOException an error occurred during string generation.
     */
    public String generateNTLM1Header() throws IOException {
        NTLMType1Message msg1 = new NTLMType1Message(m_domain,m_hostname);
        String msg1Str = msg1.exportBase64();
        return "NTLM "+msg1Str;
    }

    /**
     * ---------------------------------------------------------------------
     * Extract the nonce from a NTLM Type 2 message header in base 64 encoding.
     *
     * @param header The string in form of "NTLM XXXXXXXXXXXXXXXX"
     * @exception IllegalArgumentException If the header is not in the right
     *     format.
     */
    public void parseNTLM2Nonce(String header) throws IllegalArgumentException {
        int index = header.toLowerCase().indexOf("ntlm ");
        if (index < 0) throw new IllegalArgumentException("No NTLM header found");
        String str = header.substring(index+"ntlm ".length(),header.length()).trim();

        try {
            NTLMType2Message msg2 = new NTLMType2Message();
            msg2.parseBase64(str);
            m_nonce = msg2.getNonce();
        } catch (IOException e) {
            throw new IllegalArgumentException(e.getMessage());
        }
    }

    /**
     * ---------------------------------------------------------------------
     * Generates the 3rd step in NTLM authentication.  Requires that
     * parseNTLM2Nonce() was called and nonce is non-null.
     *
     * @return    "NTLM XXXXXXXXXX" where XXXX is the type 3 message in Base64.
     * @exception IllegalStateException No nonce exists.
     * @exception IllegalArgumentException An error occurred while generation
     *      based on the initialization parameters.
     */
    public String generateNTLM3Header() throws IllegalStateException, IllegalArgumentException {
        if (m_nonce == null) {
            throw new IllegalStateException("No nonce");
        }

        NTLMType3Message msg3 = new NTLMType3Message(m_domain,m_hostname,m_username,m_password,m_nonce);

        try {
            return "NTLM "+msg3.exportBase64();
        } catch (IOException e) {
            throw new IllegalArgumentException(e.getMessage());
        }
    }

    /**
     * ---------------------------------------------------------------------
     */
    public byte[] getNonce() {
        return m_nonce;
    }
}